package seiacpsjava.utilities;

public class MemoryStatistics {
	
	private long totalMemoryExecutionTotal = 0;
	private long freeMemoryExecutionTotal = 0;
	private long usedMemoryExecutionTotal = 0;
	private int numberOfMemoryReadings = 0;
	
	private long totalMemoryRunningAvg = 0;
	private long freeMemoryRunningAvg = 0;
	private long usedMemoryRunningAvg = 0;
	
	private final static long ONE_KB = 1024;
	private final static long ONE_MEG = ONE_KB * ONE_KB;
	
	
	public void updateMemoryTotals() {
		totalMemoryExecutionTotal += Runtime.getRuntime().totalMemory();
		freeMemoryExecutionTotal += Runtime.getRuntime().freeMemory();
		usedMemoryExecutionTotal += totalMemoryExecutionTotal - freeMemoryExecutionTotal;
		numberOfMemoryReadings++;
	}
	
	
	public void calculateMemoryRunningAvg() {
		totalMemoryRunningAvg = totalMemoryExecutionTotal / numberOfMemoryReadings;
		freeMemoryRunningAvg = freeMemoryExecutionTotal / numberOfMemoryReadings;
		usedMemoryRunningAvg = totalMemoryRunningAvg - freeMemoryRunningAvg;
		//System.out.println(toString());
	}

	@Override
	public String toString() {
		return "MemoryStatistics in MB [totalMemoryExecutionTotal="
				+ convertToMB(totalMemoryExecutionTotal) + ", freeMemoryExecutionTotal="
				+ convertToMB(freeMemoryExecutionTotal) + ", usedMemoryExecutionTotal="
				+ convertToMB(usedMemoryExecutionTotal) + ", numberOfMemoryReadings="
				+ numberOfMemoryReadings + ", totalMemoryRunningAvg="
				+ convertToMB(totalMemoryRunningAvg) + ", freeMemoryRunningAvg="
				+ convertToMB(freeMemoryRunningAvg) + ", usedMemoryRunningAvg="
				+ convertToMB(usedMemoryRunningAvg) + "]";
	}
	
	public String convertToMB(long memoryInBytes) {
		return String.valueOf(memoryInBytes / ONE_MEG);
	}


	public long getTotalMemoryExecutionTotal() {
		return totalMemoryExecutionTotal;
	}


	public long getFreeMemoryExecutionTotal() {
		return freeMemoryExecutionTotal;
	}


	public long getUsedMemoryExecutionTotal() {
		return usedMemoryExecutionTotal;
	}


	public int getNumberOfMemoryReadings() {
		return numberOfMemoryReadings;
	}


	public long getTotalMemoryRunningAvg() {
		return totalMemoryRunningAvg;
	}


	public long getFreeMemoryRunningAvg() {
		return freeMemoryRunningAvg;
	}


	public long getUsedMemoryRunningAvg() {
		return usedMemoryRunningAvg;
	}
	
	public String getTotalMemoryRunningAvgInMB() {
		return convertToMB(this.totalMemoryRunningAvg);
	}
	
	public String getFreeMemroyRunningAvgInMB() {
		return convertToMB(this.freeMemoryRunningAvg);
	}
	
	public String getUsedMemoryRunningAvgInMB() {
		return convertToMB(this.usedMemoryRunningAvg);
	}
}
